$(function () {

    showUnread();

    /**
     * 上传头像
     */
    $("#pcus-avatar").change(function() {
        var formData = new FormData();
        formData.append('ajaxupfile', $('#pcus-avatar').get(0).files[0]);
        $('#pcus-avatar').val('');
        $.ajax({
            url:IM_toget_config.ajaxupimg,
            method: 'post',
            data: formData,
            dataType: 'json',
            processData: false,
            contentType: false,
            cache: false,
            async: false,
            success: function(res) {
                if (res.errno == 0) {
                    $('#pavatar-src').val(res.data[0]);
                    $('.img-avatar').attr('src',res.data[0]);
                }
            }
        });
    });

    /**
     * 开关
     */
    $('input[type="checkbox"]').click( function() {
        $(this).toggle2classes('on', 'off');
    });

    /**
     * 点击插件一级菜单
     */
    $('.nav-drawer>.nav-item').click( function() {
        var obj  = $(this);
        if (!obj.hasClass('plugins')) {
            obj.addClass('nav-item-has-subnav active open').siblings()
                .removeClass('nav-item-has-subnav active open');
        }
    });

    /**
     * 点击插件一级菜单
     */
    $('.nav-drawer>.plugins').click( function() {
        var obj  = $(this);
        var fnav = obj.find('a');
        var url  = fnav.attr('url');
        if (url) {
            var temp = '<iframe src="'+url+'" width="100%" height="100%" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling-x="no" scrolling-y="auto" allowtransparency="yes"></iframe>';
            $('.lyear-layout-content').html(temp);
            Cookies.set('cur-open-plugin-url', url);
        }
        obj.addClass('nav-item-has-subnav active open').siblings()
            .removeClass('nav-item-has-subnav active open');
    });

    /**
     * 点击插件二级菜单
     */
    $('.plugins>.nav-subnav>li').click( function() {
        var obj  = $(this);
        var fnav = obj.find('a');
        var url  = fnav.attr('url');
        if (url) {
            var temp = '<iframe src="'+url+'" width="100%" height="100%" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling-x="no" scrolling-y="auto" allowtransparency="yes"></iframe>';
            $('.lyear-layout-content').html(temp);
            Cookies.set('cur-open-plugin-url', url);
        }
        obj.addClass('active').siblings().removeClass('active');
    });

    //tab 刷新保持本页
    $("[role='tablist'] a").on('click',function(){
        location.href = $(this).attr('href') ;
    })
});

/**
 * 两个class切换
 */
$.fn.toggle2classes = function(class1, class2) {
    if(!class1 || !class2)
        return this;
    return this.each(function() {
        var $elm = $(this);
        if ($elm.hasClass(class1) || $elm.hasClass(class2))
            $elm.toggleClass(class1 +' '+ class2);
        else
            $elm.addClass(class1);
    });
};

/**
 * 显示未读个数
 */
function showUnread() {
    if (!$('.category-2').hasClass('active')) {
        // var number = Cookies.get('unread_number');
        unread('getcount','',function (result) {
            console.log('showUnread',result);
            var number = result.number;
            if (number && number != 0) {
                $('.category-2 .notice-icon').show().text(number);
            }
        });

    } else {
        // Cookies.set('unread_number', 0);
        unread('clean');
    }
}

/**
 * 判断是否是电脑端
 * @returns {boolean}
 * @constructor
 */
function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

/**
 * 提示弹窗
 * @param msg
 * @returns {boolean}
 */
function we_im_msg(msg) {
    layer.msg('<i class="iconfont icon-zhengpinbaozhangduigou"></i><span>'+msg+'</span>', {
        // offset: 't',
        anim: 2,
        // time:500000,
        skin: 'we-im-message'
    });
    return false;
}

/**
 * 设置客服状态
 */
function setState(state) {

}

/**
 * 修改个人资料
 */
function editAccount(obj) {
    var avatar = $.trim($('#pavatar-src').val());
    var nick = $.trim($('#cus-nick').val());
    var phone = $.trim($('#cus-phone').val());
    var email = $.trim($('#cus-email').val());
    var group_id = $.trim($('#cus-group_id').val());
    if (!nick) {
        return we_im_msg('昵称不能为空');
    }
    $.ajax({
        type: "post",
        data: {
            avatar:avatar,
            nick:nick,
            phone:phone,
            email:email,
            group_id:group_id
        },
        url: IM_toget_config.editAccount,
        dataType: "json",
        success : function(r) {
            we_im_msg(r.data);
            if (r.code == 200) {
                $('.img-avatar').attr({
                    'src': avatar,
                    'alt': nick
                });
                $('.user-nick').text(nick);
                setTimeout(function() {
                    $(obj).siblings('.btn-default').click();
                },2000);
            }
        }
    });
}

/**
 * 修改密码
 */
function editPass(obj) {
    var old_upass = $.trim($('#old-upass').val());
    var new_upass = $.trim($('#new-upass').val());
    var new2_upass = $.trim($('#new2-upass').val());
    if (!old_upass) return we_im_msg('旧密码不能为空');
    if (!new_upass) return we_im_msg('新密码不能为空');
    if (!new2_upass) return we_im_msg('新密码不能为空');
    if (new_upass != new2_upass) {
        return we_im_msg('两次新密码必须相同');
    }
    $.ajax({
        type: "post",
        data: {
            old_upass:old_upass,
            new_upass:new_upass,
            new2_upass:new2_upass
        },
        url: IM_toget_config.editPass,
        dataType: "json",
        success : function(r) {
            we_im_msg(r.data);
            if (r.code == 200) {
                setTimeout(function() {
                    $(obj).siblings('.btn-default').click();
                },2000);
            }
        }
    });
}

/**
 * 安全退出
 */
function logout() {
    $.get(IM_toget_config.logout, function(res) {
        if (res.code == 200) {
            we_im_msg('退出成功');
            setTimeout(function() {
                window.location.href = res.url;
            },2000);
        }
    });
}

/**
 * 判断数组
 * @param search
 * @param array
 * @returns {boolean}
 */
function in_array(search, array) {
    for(var i in array){
        if(array[i] == search) {
            return true;
        }
    }
    return false;
}


/* 一些方法 */
function reloaded(){
    var tab = getRequest();
    if( tab ){
        $("[role='tablist'] li.active").removeClass('active') ;
        //$(".nav-tabs li.active").removeClass('active') ;
        $("[role='tablist'] [href="+tab+"]").parents('li').addClass('active') ;
        $("[role='tabpanel'].active").removeClass('active') ;
        $(tab).addClass('active') ;
    }
}

function getRequest() {
    var str = location.href
    var num = str.split("#");
    //str = str.substr(num + 1);
    if( num.length > 1 ){
        return '#'+num[1];
    }
    return '';
}

function unread(type,params,fun){
    try{
        var formData = new FormData();
        formData.append('type', type);
        formData.append('params', params);
        $.ajax({
            url: IM_toget_config.unreadadmin,
            method: 'post',
            data: formData,
            dataType: 'json',
            processData: false,
            contentType: false,
            cache: false,
            // async: false,
            success: function (res) {
                console.log(res);
                if (typeof(fun) == 'function') fun(res);
            }
        });
    }catch(e){
        
    }
}